<script lang="ts" setup>
import { APPEARANCE_KEY } from '../shared/shared.ts';
import { inject, Ref, ref } from 'vue';
import VPSwitch from './VPSwitch.vue';
import VPIconSun from './icons/VPIconSun.vue';
import VPIconMoon from './icons/VPIconMoon.vue';

const toggle = typeof localStorage !== 'undefined' ? useAppearance() : () => {};

function useAppearance() {
    const query = window.matchMedia('(prefers-color-scheme: dark)');
    const classList = document.documentElement.classList;
    /**调整主题设置 */
    const userPreference = inject('current-theme') as Ref<string>;
    const changeTheme = inject('change-theme') as Function;

    let isDark = userPreference.value === 'auto' ? query.matches : userPreference.value === 'dark';

    query.onchange = (e) => {
        if (userPreference.value === 'auto') {
            setClass((isDark = e.matches));
        }
    };

    function toggle() {
        setClass((isDark = !isDark));

        let tuserPreference = isDark ? (query.matches ? 'auto' : 'dark') : query.matches ? 'light' : 'auto';
        // 变更主题
        changeTheme(tuserPreference);
        localStorage.setItem(APPEARANCE_KEY, tuserPreference);
    }

    function setClass(dark: boolean): void {
        classList[dark ? 'add' : 'remove']('dark');
    }
    // 通知变更主题

    return toggle;
}
</script>

<template>
    <VPSwitch class="VPSwitchAppearance" aria-label="toggle dark mode" @click="toggle">
        <VPIconSun class="sun" />
        <VPIconMoon class="moon" />
    </VPSwitch>
</template>

<style scoped>
.sun {
    opacity: 1;
}

.moon {
    opacity: 0;
}

.dark .sun {
    opacity: 0;
}

.dark .moon {
    opacity: 1;
}

.dark .VPSwitchAppearance :deep(.check) {
    transform: translateX(18px);
}
</style>
